#include <cstring>
#include <cassert>
#include <cstdio>
using namespace std;
////////////////////////////strlen//////////////////////////////////////////
// 函数递归
int my_strlen1(const char *str)
{
    if (*str == '\0')
        return 0;
    else
        return 1 + my_strlen1(str + 1);
}

// 指针
size_t my_strlen2(const char *str)
{
    const char *end = str;
    // while (*end++);
    while (*end != '\0')
        end++;

    return end - str - 1;
}
// 计数器
size_t my_strlen3(const char *str)
{
    assert(str);
    size_t count = 0;
    while (*str != '\0')
    {
        count++;
        str++;
    }
    return count;
}
////////////////////////////strlen//////////////////////////////////////////

////////////////////////////strcpy//////////////////////////////////////////

// 将src(包括\0)复制到dest
char *my_strcpy(char *dest, const char *src)
{
    char *cur = dest;
    while ((*cur++ = *src++) != '\0')
        ;
    return dest;
}
/*
从src复制n个字符到dest
src < n 如3 5 复制src+\0 用\0填充剩余空间
src > n 如5 3 复制前n个字符 不添加\0
*/
char *my_strncpy(char *dest, const char *src, size_t n)
{
    char *ret = dest;
    while (n > 0 && *src != '\0')
    {
        *dest++ = *src++;
        n--;
    }
    // 填充剩余的n个字符为'\0'
    while (n--)
        *dest++ = '\0';

    return ret;
}
////////////////////////////strcpy//////////////////////////////////////////

int my_strcmp(const char *str1, const char *str2)
{
    while (*str1 && (*str1 == *str2))
    {
        str1++;
        str2++;
    }
    return (unsigned char)(*str1) - (unsigned char)(*str2);
}

char *my_strcat(char *dest, const char *src)
{
    assert(dest && src);

    char *ret = dest;
    while (*dest)
        dest++;
    while ((*dest++ = *src++))
    {
    }
    return ret;
}
char *my_strncat(char *p, const char *q, size_t n)
{
    char *ret = p;
    while (*p)
        *p++;
    while (n--)
    {
        if ((*p++ = *q++) == 0)
            return ret;
    }
    *p = '\0';
    return ret;
}
char *my_strstr(const char *str1, const char *str2)
{
    if (str2 == nullptr || *str2 == '\0')
        return (char *)str1;

    char *cur = (char *)str1;
    char *s1, *s2;
    while (*cur)
    {
        s1 = cur;
        s2 = (char *)str2;
        while (*s1 && *s2 && *s1 == *s2)
            s1++, s2++;
        if (*s2 == '\0')
            return cur;
        cur++;
    }
    return NULL;
}

char *my_strtok(char *str, const char *dmt)
{                          
    static char *p = NULL; 
    if (str != NULL)       
        p = str;
    char dmtHash[256] = {0};
    while (*dmt) 
        dmtHash[*dmt++] = 1;
    char *ret = *p ? p : NULL;
    // 最后一个字符串得到后，p指向整个字符串的\0
    // 再次调用，ret返回NULL，调用结束，主函数for循环也结束
    while (*p && dmtHash[*p] == 0)
        p++; 
    if (*p)  
        *p++ = '\0';
    return ret;
}
